﻿<?PHP
require_once("base.wpfb.php");
require_once ('src/facebook.php');

class Table2wp{

private $globalVars = null;
private $entryPageName = null;

public function __construct($pageParent) {
	$this->globalVars = new WPFB($pageParent);
	$this->entryPageName = $pageParent;
}

private function pushTable2wp_UI($groupList)
{
	if (count($groupList) == 0 )
		return;
?>
	<h1>Select the group id and select the criteria</h1>
	<form enctype="multipart/form-data" action="<?php echo get_bloginfo('wpurl') . '/wp-admin/admin.php?page=' . $this->entryPageName ?>" method="GET">
		<strong>Group-id:</strong>
		<?PHP 
		echo "<select name='show_group_id'>";
		foreach($groupList as $rows)
		{
			echo "<option value='{$rows['group_id']}'>{$rows['name']}</option>";
		}
		echo "</select>";
		?>
		<br/>
		<strong>Criteria:</strong> <br/>
		<input type="radio" name="sort_order" value="like_count" />Top 50 post by like-count <br/>
		<input type="radio" name="sort_order" value="latest" checked /> latest 50 post <br/>
		<input type="radio" name="sort_order" value="weekly" id='sort_order' /> Week: 
		<input type='text' onfocus="select();jQuery('#sort_order').attr('checked','checked');" size=3 name='weekNo' value='-1' /> <br/>
		<input type="radio" name="sort_order" value="author" id='author' /> By Author-id: 
		<input type='text' onfocus="select();jQuery('#author').attr('checked','checked');" size=20 name='author' value='-1' /> <br/>
		<small><code>select A.*
from wpfb_group_post_collection A
where A.from_group_id = '368809433220789' and A.from_name like 'Jewel%'
order by A.message_creation_time</code></small>
		<input type='hidden' name='page' value='<?PHP echo $this->entryPageName; ?>' />
		<br/><br/>
		<input type="submit" class="submit button button-primary" value="Submit">
	</form>
<?PHP 
}

public function pushTable2wp()
{
	try{
		$databaseRowsAsTR = null;
		$postFirstLine = null;
		
		$groupList = null;
		$groupList = $this->globalVars->select_ACVWBWPERIDFGLD76KS();

		if(count($groupList) ==0)
			throw new Exception("Please save some data into server first");		
			
		if( !isset($_GET['show_group_id']) || !is_numeric($_GET['show_group_id']) )
		{
			throw new Exception("Please save some data into server first");		
			return;
		}
		
		
		$groupName = null;
		foreach($groupList as $rows)
		{
			if( $rows['group_id'] == $_GET['show_group_id'])
				$groupName = $rows['name'];
		}
		if( $groupName == null)
			throw new Exception('Given group id has no saved data in database');
			
		if( isset($_GET['sort_order']) &&  $_GET['sort_order'] == 'like_count')
		{
			$databaseRowsAsTR = $this->getLatestDataFromDatabase($_GET['show_group_id'],'like_count');
			$postFirstLine = 'পোস্টসমূহ সিলেকশন: like-count এর ভিত্তিতে';
		}
		else if( isset($_GET['sort_order']) &&  $_GET['sort_order'] == 'weekly')
		{
			if( !is_numeric($_GET['weekNo']) || !($_GET['weekNo']>=1 && $_GET['weekNo']<=53) )
				throw new Exception('Week number must be numeric and between 1~53.');
			$databaseRowsAsTR = $this->getWhereFilteredDataFromDatabase($_GET['show_group_id'],$_GET['weekNo'],'weekNo');
			$year= date('Y');
			$postFirstLine = "পোস্টসমূহের ব্যাপ্তি: [সপ্তাহ={$_GET['weekNo']}, সাল={$year}]";
		}
		else if( isset($_GET['sort_order']) &&  $_GET['sort_order'] == 'author')
		{
			if( !is_numeric($_GET['author']) || $_GET['author']<0)
				throw new Exception('Author-id must be numeric and greater than 0.');
			$databaseRowsAsTR = $this->getWhereFilteredDataFromDatabase($_GET['show_group_id'],$_GET['author'],'author');
			$postFirstLine = "নির্বাচিত তালিকা: {$_GET['author']}";
		}
		else
		{
			$databaseRowsAsTR = $this->getLatestDataFromDatabase($_GET['show_group_id'],'message_creation_time');
			$postFirstLine = 'পোস্টসমূহ সিলেকশন: message_creation_time এর ভিত্তিতে';
		}	
		
		if(strlen($databaseRowsAsTR) == 0)
		{
			$_GET['groupName'] = $groupName;
			throw new Exception('Cannot find any post for given inputs: <code>' . print_r($_GET, true) .'</code>');
		}
		$this->pushDatabaseRowsToWordpress($databaseRowsAsTR, $postFirstLine, $groupName .' >> '. $_GET['sort_order'], $_GET['show_group_id']);
		$this->pushTable2wp_UI($groupList);
		
	}catch(Exception $e)
	{ 
		$this->globalVars->printException($e);
		$this->pushTable2wp_UI($groupList);
	}
}


private function pushDatabaseRowsToWordpress($databaseRowsAsTR, $postFirstLine, $postTitle, $group_id)
{
	$postData = null;
	
	$postData = "<div><script type='text/javascript' src='//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js'></script>";
	$postData .= '<style type="text/css">@import url("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css");</style></div>';
	
	//related to issue#21 in http://code.google.com/p/buetian-dot-com-theme-wordpress/issues/detail?id=21
	$table_id = strval(time()) . '_' . strval(rand()) . '_' . $group_id;
	$postData .= "<div style='width:600px;'><table id='{$table_id}' class='display'><thead style='background:#EEEEEE'>";
	//$postData .= "<tr>/*<th>Written by</th><th>Content</th>";
	$postData .= "<tr><th>Like #</th><th>Comment #</th><th>Permalink</th></tr>";
    $postData .= "</thead><tbody>{$databaseRowsAsTR}</tbody></table></div>";
	
	$postData .= '<script type="text/javascript" charset="utf-8">';
	$postData .= "(function($){	$('#{$table_id}').dataTable({'aaSorting': [[ 0, 'desc' ]]} );})(jQuery)";
	$postData .= '</script>';
	
	//echo $postData;
	/* Insert into wordpress */
	global $current_user;
	$my_post = array(
		'post_title' => $postTitle,
		'post_content' => "<h1>$postFirstLine</h1>" . $postData,
		'tags_input' => array("Group id: $group_id"),
		'post_author' => $current_user->ID,
		'post_status' => 'pending',
		'filter' => true,
		'post_excerpt' => $postFirstLine
	);
	
	$post_id = wp_insert_post( $my_post, $wp_error );
	if($wp_error)
		throw new Exception($wp_error->get_error_message());
		
	$url = get_bloginfo('wpurl') . "?p=$post_id";
	ECHO "<h2>Successfully posted in web: <a target='_blank' href='$url'>$url</a></h2><hr/>";
}


private function getWhereFilteredDataFromDatabase($group_id, $valueOfWhich, $which)
{
	$databaseRows = $this->globalVars->select_XCNVWKERSDLMC485DK($group_id,$valueOfWhich, $which);
	return $this->getRawDataFromDatabase($databaseRows);
}
private function getLatestDataFromDatabase($group_id,$sort_order)
{
	$databaseRows = $this->globalVars->select_KCVPWEFCMV495KL($group_id,$sort_order);
	return $this->getRawDataFromDatabase($databaseRows);
}


private function getRawDataFromDatabase($databaseRows)
{
	$databaseRowsAsTR = "";
	
	if( count($databaseRows) > 0)
	{
		foreach ($databaseRows as $rows)
		{
			$databaseRowsAsTR .= '<tr>';
			//$databaseRowsAsTR .= "<td>{$rows['from_name']}</td>";
			//$databaseRowsAsTR .= "<td>". htmlspecialchars($rows['message']) . "</td>";
			$databaseRowsAsTR .= "<td>{$rows['like_count']}</td>";
			$databaseRowsAsTR .= "<td>{$rows['comment_count']}</td>";
			$databaseRowsAsTR .= "<td><a target='_blank' href='{$rows['message_permalink']}'>{$rows['message_creation_time']}</a></td>";
			$databaseRowsAsTR .='</tr>';
			//break;
		}
		//print_r($databaseRows);
	}
	return $databaseRowsAsTR;
}


} // class ends here
?>